﻿using DayuCode.Designer.Common;
using DayuCode.Designer.Entity;
using DayuCode.Designer.Model;
using DayuCode.Designer.Service;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DayuCode.Designer.Forms
{
    public partial class FormProject : UIForm
    {
        ProjectVO projectVO;
        Project project;
        UploadFileInfo uploadFileInfo;
        public FormProject(long projectId, long catalogId)
        {
            InitializeComponent();
            this.projectVO = ProjectHandler.getProjectVO(projectId);
            this.project = projectVO.Project;
            if (this.project == null)
            {
                project = new Project();
                project.CatalogId = catalogId;
                projectVO.Project = project;
            }
            cmbDbType.DataSource = projectVO.DbTypes;
            CodeItem dbType = projectVO.DbTypes.Find(it => it.Code == project.DbType);
            if(dbType != null)
            {
                cmbDbType.SelectedItem = dbType;
            }
            txtName.Text = project.Name;
            txtCode.Text = project.Code;
            txtPdmName.Text = project.PdmFileName;
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                this.uploadFileInfo = ProjectHandler.uploadPdmFile(fileName);
                txtPdmName.Text = uploadFileInfo.OrgFileName;
                this.ShowSuccessTip("pdm文件已上传成功");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string name = txtName.Text.Trim();
            string code = txtCode.Text.Trim();

            if (string.IsNullOrEmpty(name))
            {
                ShowErrorTip("中文名称不能为空");
                return;
            }
            if (string.IsNullOrEmpty(code))
            {
                ShowErrorTip("英文不能为空");
                return;
            }

            project.Name = name;
            project.Code = code;
            CodeItem dbType = cmbDbType.SelectedItem as CodeItem;
            if (dbType != null)
            {
                project.DbType = dbType.Code;
            }
            if (this.uploadFileInfo != null)
            {
                project.PdmFileName = this.uploadFileInfo.OrgFileName;
                project.PdmFilePath = this.uploadFileInfo.NewFileName;
            }
            project = ProjectHandler.saveProject(project);
            DialogResult = DialogResult.OK;
        }

        public Project Project
        {
            get { return project; }
        }
    }
}
